﻿using HalconDotNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using thinger.VisionModels;

namespace thinger.VisitionDAL
{

    public class ShapeModelHelper
    {
        private HalconHelper halcon = new HalconHelper();

        /// <summary>
        /// 创建模板
        /// </summary>
        /// <param name="hWindowHandle"></param>
        /// <param name="hImage"></param>
        /// <param name="matchParams"></param>
        /// <returns></returns>
        public OperateResult CreateShapeModel(HTuple hWindowHandle, HObject hImage, MatchParams matchParams)
        {
            try
            {
                //提示
                halcon.disp_message(hWindowHandle, "请绘制模板区域，完成后鼠标右击确认", "window", 20, 20, "red", "false");

                //Draw
                HOperatorSet.DrawRectangle2(hWindowHandle, out HTuple row, out HTuple column, out HTuple phi, out HTuple length1, out HTuple length2);

                //Gen
                HOperatorSet.GenRectangle2(out matchParams.modelRegion, row, column, phi, length1, length2);

                //ReduceDomain
                HOperatorSet.ReduceDomain(hImage, matchParams.modelRegion, out HObject imageReduced);

                //Clear
                ClearShapeMode(ref matchParams.modelId);

                //Create
                HOperatorSet.CreateShapeModel(imageReduced, "auto", matchParams.startAngle, matchParams.rangeAngle, "auto", "auto", "use_polarity", "auto", "auto", out matchParams.modelId);

                HOperatorSet.DispObj(hImage, hWindowHandle);

                HOperatorSet.DispObj(matchParams.modelRegion, hWindowHandle);

                if (matchParams.modelId != null)
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板成功", "window", 20, 20, "green", "false");

                    return OperateResult.CreateSuccessResult();
                }
                else
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板失败", "window", 20, 20, "red", "false");

                    return OperateResult.CreateFailResult("创建模板失败，未查找到模板");
                }
            }
            catch (Exception ex)
            {
                //提示
                halcon.disp_message(hWindowHandle, "创建模板失败：" + ex.Message, "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("创建模板失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 创建模板
        /// </summary>
        /// <param name="hWindowHandle"></param>
        /// <param name="hImage"></param>
        /// <param name="matchParams"></param>
        /// <returns></returns>
        public OperateResult CreateShapeModel_new(HTuple hWindowHandle, HObject hImage, MatchParams matchParams)
        {
            try
            {
                //提示
                halcon.disp_message(hWindowHandle, "请绘制模板区域，完成后鼠标右击确认", "window", 20, 20, "red", "false");

                //Draw
                HOperatorSet.DrawRectangle2(hWindowHandle, out HTuple row, out HTuple column, out HTuple phi, out HTuple length1, out HTuple length2);

                //Gen
                HOperatorSet.GenRectangle2(out matchParams.modelRegion, row, column, phi, length1, length2);

                //ReduceDomain
                HOperatorSet.ReduceDomain(hImage, matchParams.modelRegion, out HObject imageReduced);

                //Clear
                ClearShapeMode(ref matchParams.modelId);

                //Create
                HOperatorSet.CreateScaledShapeModel(imageReduced, "auto", matchParams.startAngle, matchParams.rangeAngle, "auto", 0.76, 1.31,
                  "auto", (new HTuple("point_reduction_high")).TupleConcat("no_pregeneration"),
                  "use_polarity", ((new HTuple(74)).TupleConcat(110)).TupleConcat(228), 6,
                  out matchParams.modelId);


                //HOperatorSet.CreateShapeModel(imageReduced, "auto", matchParams.startAngle, matchParams.rangeAngle, "auto", "auto", "use_polarity", "auto", "auto", out matchParams.modelId);

                HOperatorSet.DispObj(hImage, hWindowHandle);

                HOperatorSet.DispObj(matchParams.modelRegion, hWindowHandle);

                if (matchParams.modelId != null)
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板成功", "window", 20, 20, "green", "false");

                    return OperateResult.CreateSuccessResult();
                }
                else
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板失败", "window", 20, 20, "red", "false");

                    return OperateResult.CreateFailResult("创建模板失败，未查找到模板");
                }
            }
            catch (Exception ex)
            {
                //提示
                halcon.disp_message(hWindowHandle, "创建模板失败：" + ex.Message, "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("创建模板失败：" + ex.Message);
            }
        }
        //---新模板创建
        public OperateResult CreateScaledShapeModel(HTuple hWindowHandle, HObject hImage, MatchParams matchParams)
        {
            try
            {
                //提示
                halcon.disp_message(hWindowHandle, "请绘制模板区域，完成后鼠标右击确认", "window", 20, 20, "red", "false");

                //Draw
                HOperatorSet.DrawRectangle2(hWindowHandle, out HTuple row, out HTuple column, out HTuple phi, out HTuple length1, out HTuple length2);

                //Gen
                HOperatorSet.GenRectangle2(out matchParams.modelRegion, row, column, phi, length1, length2);

                //ReduceDomain
                HOperatorSet.ReduceDomain(hImage, matchParams.modelRegion, out HObject imageReduced);

                //Clear
                ClearShapeMode(ref matchParams.modelId);
                // 参数：1.内容区域 2.金字塔级别 3.初始角度  4.模板旋转角度范围,>=0  5.AngleStep,//旋转角度的步长，>=0 and <=pi/16
                //6.缩放比例最小值   7.缩放比例最大值 9.比例范围内的步长  10.Optimization,//设置模板优化和模板创建方法   11. Metric, //匹配方法设置
                //12.Contrast,//可选最小尺寸设置对比度   13. MinContrast ://设置最小对比度   12.模板句柄id
                HOperatorSet.CreateScaledShapeModel(imageReduced, 5, (new HTuple(0)).TupleRad()
                    , (new HTuple(360)).TupleRad(), (new HTuple(0.0921)).TupleRad(), 0.76, 1.31,
                    0.0008, (new HTuple("point_reduction_high")).TupleConcat("no_pregeneration"),
                    "use_polarity", ((new HTuple(74)).TupleConcat(110)).TupleConcat(228), 6,
                    out matchParams.modelId);


                HOperatorSet.DispObj(hImage, hWindowHandle);

                HOperatorSet.DispObj(matchParams.modelRegion, hWindowHandle);

                if (matchParams.modelId != null)
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板成功", "window", 20, 20, "green", "false");

                    return OperateResult.CreateSuccessResult();
                }
                else
                {
                    //提示
                    halcon.disp_message(hWindowHandle, "创建模板失败", "window", 20, 20, "red", "false");

                    return OperateResult.CreateFailResult("创建模板失败，未查找到模板");
                }
            }
            catch (Exception ex)
            {
                //提示
                halcon.disp_message(hWindowHandle, "创建模板失败：" + ex.Message, "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("创建模板失败：" + ex.Message);
            }
        }
        public OperateResult FindScaledShapeModel(HTuple hWindowHandle, HObject hoImage, MatchParams matchParams)
        {

            try
            {
                // Local iconic variables 

                HObject ho_Image, ho_ModelRegion, ho_TemplateImage;
                HObject ho_ModelContours;

                // Local control variables 

                HTuple hv_ModelId = null, hv_ModelRow = null;
                HTuple hv_ModelColumn = null, hv_ModelAngle = null, hv_ModelScale = null;
                HTuple hv_ModelScore = null;
                // Initialize local and output iconic variables 
                HOperatorSet.GenEmptyObj(out ho_Image);
                HOperatorSet.GenEmptyObj(out ho_ModelRegion);
                HOperatorSet.GenEmptyObj(out ho_TemplateImage);
                HOperatorSet.GenEmptyObj(out ho_ModelContours);
                //Matching 01: BEGIN of generated code for model initialization
                HOperatorSet.SetSystem("border_shape_models", "false");
                //Matching 01: Obtain the model image
                ho_Image.Dispose();
                HOperatorSet.ReadImage(out ho_Image, "D:/new3/2.bmp");
                //Matching 01: build the ROI from basic regions
                ho_ModelRegion.Dispose();
                HOperatorSet.GenRectangle1(out ho_ModelRegion, 472.774, 1052.95, 2602.5, 3169.35);
                //Matching 01: reduce the model template
                ho_TemplateImage.Dispose();
                HOperatorSet.ReduceDomain(ho_Image, ho_ModelRegion, out ho_TemplateImage);
                //Matching 01: create the shape model
                HOperatorSet.CreateScaledShapeModel(ho_TemplateImage, 5, (new HTuple(0)).TupleRad()
                    , (new HTuple(360)).TupleRad(), (new HTuple(0.0921)).TupleRad(), 0.76, 1.31,
                    0.0008, (new HTuple("point_reduction_high")).TupleConcat("no_pregeneration"),
                    "use_polarity", ((new HTuple(74)).TupleConcat(110)).TupleConcat(228), 6,
                    out hv_ModelId);
                //Matching 01: get the model contour for transforming it later into the image
                ho_ModelContours.Dispose();
                //HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelId, 1);
                //Matching 01: END of generated code for model initialization
                //Matching 01: BEGIN of generated code for model application
                //Matching 01: the following operations are usually moved into
                //Matching 01: that loop where the aquired images are processed
                //Matching 01: Find the model
                HOperatorSet.FindScaledShapeModel(hoImage, hv_ModelId, (new HTuple(0)).TupleRad()
                    , (new HTuple(360)).TupleRad(), 0.76, 1.31, 0.29, 1, 0.5, "least_squares",
                    (new HTuple(5)).TupleConcat(1), 0.75, out hv_ModelRow, out hv_ModelColumn,
                    out hv_ModelAngle, out hv_ModelScale, out hv_ModelScore);
                //获取中心点十字架
                HOperatorSet.GenCrossContourXld(out HObject cross1, hv_ModelRow, hv_ModelColumn, 200, new HTuple(200));
                Console.WriteLine("当前角度：" + hv_ModelAngle.TupleDeg().ToString());

                string jiaodu = hv_ModelAngle.TupleDeg().ToString();
                Single x, y;
                x = Convert.ToSingle(hv_ModelRow.D);
                y = Convert.ToSingle(hv_ModelColumn.D);

                HOperatorSet.DispObj(hoImage, hWindowHandle);

                //HOperatorSet.DispObj(ho_ModelRegion, hWindowHandle);
                //HOperatorSet.DispObj(ho_TemplateImage, hWindowHandle);
                //HOperatorSet.DispObj(ho_ModelContours, hWindowHandle);
                HOperatorSet.DispObj(cross1, hWindowHandle);
                //提示
                halcon.disp_message(hWindowHandle, "查找模板成功", "window", 20, 20, "green", "false");
                return new OperateResult()
                {
                    IsSuccess = true,
                    Message = jiaodu + "," + x + "," + y
                };
            }
            catch (Exception)
            {

                halcon.disp_message(hWindowHandle, "查找模板失败", "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("查找模板失败：未查找到模板");
            }


        }


        // 新查找模板
        public OperateResult FindAction(HTuple hWindowHandle, HObject hoImage)
        {

            try
            {
                // Local iconic variables 

                HObject ho_Image,ho_ModelRegion, ho_TemplateImage;
                HObject ho_ModelContours;

                // Local control variables 

                HTuple hv_ModelId = null, hv_ModelRow = null;
                HTuple hv_ModelColumn = null, hv_ModelAngle = null, hv_ModelScale = null;
                HTuple hv_ModelScore = null;
                // Initialize local and output iconic variables 
                HOperatorSet.GenEmptyObj(out ho_Image);
                HOperatorSet.GenEmptyObj(out ho_ModelRegion);
                HOperatorSet.GenEmptyObj(out ho_TemplateImage);
                HOperatorSet.GenEmptyObj(out ho_ModelContours);
                //Matching 01: BEGIN of generated code for model initialization
                HOperatorSet.SetSystem("border_shape_models", "false");
                //Matching 01: Obtain the model image
                ho_Image.Dispose();
                HOperatorSet.ReadImage(out ho_Image, "D:/new3/2.bmp");
                //Matching 01: build the ROI from basic regions
                ho_ModelRegion.Dispose();
                HOperatorSet.GenRectangle1(out ho_ModelRegion, 472.774, 1052.95, 2602.5, 3169.35);
                //Matching 01: reduce the model template
                ho_TemplateImage.Dispose();
                HOperatorSet.ReduceDomain(ho_Image, ho_ModelRegion, out ho_TemplateImage);
                //Matching 01: create the shape model
                HOperatorSet.CreateScaledShapeModel(ho_TemplateImage, 5, (new HTuple(0)).TupleRad()
                    , (new HTuple(360)).TupleRad(), (new HTuple(0.0921)).TupleRad(), 0.76, 1.31,
                    0.0008, (new HTuple("point_reduction_high")).TupleConcat("no_pregeneration"),
                    "use_polarity", ((new HTuple(74)).TupleConcat(110)).TupleConcat(228), 6,
                    out hv_ModelId);
                //Matching 01: get the model contour for transforming it later into the image
                ho_ModelContours.Dispose();
                //HOperatorSet.GetShapeModelContours(out ho_ModelContours, hv_ModelId, 1);
                //Matching 01: END of generated code for model initialization
                //Matching 01: BEGIN of generated code for model application
                //Matching 01: the following operations are usually moved into
                //Matching 01: that loop where the aquired images are processed
                //Matching 01: Find the model
                HOperatorSet.FindScaledShapeModel(hoImage, hv_ModelId, (new HTuple(0)).TupleRad()
                    , (new HTuple(360)).TupleRad(), 0.76, 1.31, 0.29, 1, 0.5, "least_squares",
                    (new HTuple(5)).TupleConcat(1), 0.75, out hv_ModelRow, out hv_ModelColumn,
                    out hv_ModelAngle, out hv_ModelScale, out hv_ModelScore);
                //获取中心点十字架
                HOperatorSet.GenCrossContourXld(out HObject cross1, hv_ModelRow, hv_ModelColumn, 200, new HTuple(200));
                Console.WriteLine("当前角度：" + hv_ModelAngle.TupleDeg().ToString());

                string jiaodu = hv_ModelAngle.TupleDeg().ToString();
                Single x, y;
                x = Convert.ToSingle(hv_ModelRow.D);
                y = Convert.ToSingle(hv_ModelColumn.D);

                HOperatorSet.DispObj(hoImage, hWindowHandle);

                //HOperatorSet.DispObj(ho_ModelRegion, hWindowHandle);
                //HOperatorSet.DispObj(ho_TemplateImage, hWindowHandle);
                //HOperatorSet.DispObj(ho_ModelContours, hWindowHandle);
                HOperatorSet.DispObj(cross1, hWindowHandle);
                //提示
                halcon.disp_message(hWindowHandle, "查找模板成功", "window", 20, 20, "green", "false");
                return new OperateResult()
                {
                    IsSuccess = true,
                    Message = jiaodu + "," + x + "," + y
                };
            }
            catch (Exception)
            {

                halcon.disp_message(hWindowHandle, "查找模板失败", "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("查找模板失败：未查找到模板");
            }
       

        }

        /// <summary>
        /// 查找模板
        /// </summary>
        /// <param name="hWindowHandle"></param>
        /// <param name="hImage"></param>
        /// <param name="matchParams"></param>
        /// <param name="homMat2D"></param>
        /// <returns></returns>
        public OperateResult FindShapeModel_new(HTuple hWindowHandle, HObject hImage, MatchParams matchParams, out HTuple homMat2D)
        {
            homMat2D = new HTuple();

            try
            {
                //HOperatorSet.FindShapeModel(hImage, matchParams.modelId, matchParams.startAngle, matchParams.rangeAngle, matchParams.score,

                              // matchParams.numMatchs, matchParams.overlap, "least_squares", 0, matchParams.greediness, out HTuple row, out HTuple column, out HTuple angle, out HTuple score);

                HOperatorSet.FindScaledShapeModel(hImage, matchParams.modelId, matchParams.startAngle
                 , matchParams.rangeAngle, 0.76, 1.31, matchParams.score, 1, 0.5, "least_squares",
                 0, matchParams.greediness, out HTuple row, out HTuple column,
                  out HTuple angle, out HTuple Scale, out HTuple score);



                //通过判断结果，证明是否查找到模板
                if (row.Length > 0)
                {
                    //获取中心点
                    //HOperatorSet.GetShapeModelContours(out HObject ModelContours, matchParams.modelId, 1);
                    //HOperatorSet.AreaCenter(matchParams.modelRegion, out HTuple area1, out HTuple row01, out HTuple column01);
                    HOperatorSet.GenCrossContourXld(out HObject cross1, row, column, 200, new HTuple(200));

                    Single x, y;
                    x = Convert.ToSingle(row.D);
                    y = Convert.ToSingle(column.D);
                   double defen= Convert.ToSingle(score.TupleDeg().ToString());

                    //处理

                    //显示轮廓

                    //获取仿射变化矩阵
                    HOperatorSet.VectorAngleToRigid(0, 0, 0, row, column, angle, out HTuple homMat2d_T);

                    //获取轮廓
                    HOperatorSet.GetShapeModelContours(out HObject contour, matchParams.modelId, 1);

                    //将显示在0.0 位置的轮廓仿射过去并显示
                    HOperatorSet.AffineTransContourXld(contour, out HObject contour2, homMat2d_T);

                    //产生一个十字叉
                    HOperatorSet.GenCrossContourXld(out HObject cross, row, column, 20, new HTuple(45));

                    HOperatorSet.AreaCenter(matchParams.modelRegion, out HTuple area, out HTuple row0, out HTuple column0);



                    //获取圆ROI的仿射变化矩阵

                    HOperatorSet.VectorAngleToRigid(row0, column0, 0, row, column, angle, out homMat2D);


                    string jiaodu = angle.TupleDeg().ToString();

                    //显示
                    //HOperatorSet.DispObj(hImage, hWindowHandle);
                    HOperatorSet.DispObj(cross1, hWindowHandle);

                    //HOperatorSet.DispObj(contour, hWindowHandle);

                    //HOperatorSet.DispObj(contour2, hWindowHandle);

                    HOperatorSet.DispObj(cross, hWindowHandle);

                    //提示
                    halcon.disp_message(hWindowHandle, "查找模板成功", "window", 80, 80, "green", "false");
                    halcon.disp_message(hWindowHandle, "查找得分:" + defen.ToString("F2"), "window", 80, 110, "red", "true");
                    return new OperateResult()
                    {
                        IsSuccess = true,
                        Message = jiaodu + "," + x + "," + y + "," + defen.ToString("F2")
                    };
                }

                else
                {

                    //提示
                    halcon.disp_message(hWindowHandle, "查找模板失败", "window", 20, 80, "red", "false");
                   

                    return OperateResult.CreateFailResult("查找模板失败：未查找到模板");

                }

            }
            catch (Exception ex)
            {
                //提示
                halcon.disp_message(hWindowHandle, "查找模板失败：" + ex.Message, "window", 20, 80, "red", "false");

                return OperateResult.CreateFailResult("查找模板失败：" + ex.Message);
            }
        }


        /// <summary>
        /// 查找模板
        /// </summary>
        /// <param name="hWindowHandle"></param>
        /// <param name="hImage"></param>
        /// <param name="matchParams"></param>
        /// <param name="homMat2D"></param>
        /// <returns></returns>
        public OperateResult FindShapeModel(HTuple hWindowHandle, HObject hImage, MatchParams matchParams, out HTuple homMat2D)
        {
            homMat2D = new HTuple();

            try
            {
                HOperatorSet.FindShapeModel(hImage, matchParams.modelId, matchParams.startAngle, matchParams.rangeAngle, matchParams.score,

                               matchParams.numMatchs, matchParams.overlap, "least_squares", 0, matchParams.greediness, out HTuple row, out HTuple column, out HTuple angle, out HTuple score);

                //通过判断结果，证明是否查找到模板
                if (row.Length > 0)
                {
                    //获取中心点
                    //HOperatorSet.GetShapeModelContours(out HObject ModelContours, matchParams.modelId, 1);
                    //HOperatorSet.AreaCenter(matchParams.modelRegion, out HTuple area1, out HTuple row01, out HTuple column01);
                    HOperatorSet.GenCrossContourXld(out HObject cross1, row, column, 200, new HTuple(200));
                   
                    Single x, y;
                    x = Convert.ToSingle(row.D);
                    y = Convert.ToSingle(column.D);

                    //处理

                    //显示轮廓

                    //获取仿射变化矩阵
                    HOperatorSet.VectorAngleToRigid(0, 0, 0, row, column, angle, out HTuple homMat2d_T);
                    
                    //获取轮廓
                    HOperatorSet.GetShapeModelContours(out HObject contour, matchParams.modelId, 1);

                    //将显示在0.0 位置的轮廓仿射过去并显示
                    HOperatorSet.AffineTransContourXld(contour, out HObject contour2, homMat2d_T);

                    //产生一个十字叉
                    HOperatorSet.GenCrossContourXld(out HObject cross, row, column, 20, new HTuple(45));

                    HOperatorSet.AreaCenter(matchParams.modelRegion, out HTuple area, out HTuple row0, out HTuple column0);

                   

                    //获取圆ROI的仿射变化矩阵

                    HOperatorSet.VectorAngleToRigid(row0, column0, 0, row, column, angle, out homMat2D);
                

                    string jiaodu = angle.TupleDeg().ToString();

                    //显示
                    //HOperatorSet.DispObj(hImage, hWindowHandle);
                    HOperatorSet.DispObj(cross1, hWindowHandle);

                    //HOperatorSet.DispObj(contour, hWindowHandle);

                    //HOperatorSet.DispObj(contour2, hWindowHandle);

                    HOperatorSet.DispObj(cross, hWindowHandle);

                    //提示
                    halcon.disp_message(hWindowHandle, "查找模板成功", "window", 20, 20, "green", "false");
                 
                    return new OperateResult()
                    {
                        IsSuccess = true,
                        Message = jiaodu + "," + x + "," + y
                    };
                }

                else
                {

                    //提示
                    halcon.disp_message(hWindowHandle, "查找模板失败", "window", 20, 20, "red", "false");

                    return OperateResult.CreateFailResult("查找模板失败：未查找到模板");

                }

            }
            catch (Exception ex)
            {
                //提示
                halcon.disp_message(hWindowHandle, "查找模板失败：" + ex.Message, "window", 20, 20, "red", "false");

                return OperateResult.CreateFailResult("查找模板失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 存储模板
        /// </summary>
        /// <param name="path">模板存储的文件夹</param>
        /// <param name="matchParams"></param>
        /// <param name="circleParams"></param>
        /// <returns></returns>
        public OperateResult SaveShapeModel(string path, MatchParams matchParams, CircleParams circleParams)
        {
            if (matchParams.modelId != null && matchParams.modelRegion != null)
            //if (matchParams.modelId != null && matchParams.modelRegion != null && circleParams.rOI_X.Length > 0 && circleParams.rOI_Y.Length > 0)
            {

                //模板相关
                HOperatorSet.WriteShapeModel(matchParams.modelId, path + "\\model.shm");

                HOperatorSet.WriteRegion(matchParams.modelRegion, path + "\\model_region.tif");

                ////圆ROI相关

                //HOperatorSet.WriteTuple(circleParams.rOI_Y, path + "\\roi_row.tup");
                //HOperatorSet.WriteTuple(circleParams.rOI_X, path + "\\roi_col.tup");
                //HOperatorSet.WriteTuple(circleParams.circle_Direct, path + "\\roi_dir.tup");

                ////参数文本
                bool result = true;

                //IniConfigHelper.filePath = path + "\\param.ini";

                //result &= IniConfigHelper.WriteIniData("定位参数", "起始角度", matchParams.startAngle.ToString());
                //result &= IniConfigHelper.WriteIniData("定位参数", "角度范围", matchParams.rangeAngle.ToString());
                //result &= IniConfigHelper.WriteIniData("定位参数", "分数", matchParams.score.ToString());
                //result &= IniConfigHelper.WriteIniData("定位参数", "重叠度", matchParams.overlap.ToString());
                //result &= IniConfigHelper.WriteIniData("定位参数", "数量", matchParams.numMatchs.ToString());


                //result &= IniConfigHelper.WriteIniData("测量参数", "搜索点数", circleParams.circle_Elements.ToString());
                //result &= IniConfigHelper.WriteIniData("测量参数", "边缘阈值", circleParams.circle_Threshold.ToString());
                //result &= IniConfigHelper.WriteIniData("测量参数", "平滑系数", circleParams.circle_Sigma.ToString());
                //result &= IniConfigHelper.WriteIniData("测量参数", "极性", circleParams.circle_Transition.ToString());
                //result &= IniConfigHelper.WriteIniData("测量参数", "点选择", circleParams.circle_Point_Select.ToString());

                return result ? OperateResult.CreateSuccessResult() : OperateResult.CreateFailResult("保存模板失败：INI存储失败"); ;
            }
            else
            {
                return OperateResult.CreateFailResult("保存模板失败：模板参数不全");
            }
        }


        /// <summary>
        /// 加载模板
        /// </summary>
        /// <param name="path"></param>
        /// <param name="matchParams"></param>
        /// <param name="circleParams"></param>
        /// <returns></returns>
        public OperateResult<MatchParams, CircleParams> LoadShapeModel(string path)
        {
            if (Directory.Exists(path))
            {
                try
                {
                    MatchParams matchParams = new MatchParams();
                    CircleParams circleParams = new CircleParams();

                    HOperatorSet.ReadShapeModel(path + "\\model.shm", out matchParams.modelId);

                    HOperatorSet.ReadRegion(out matchParams.modelRegion, path + "\\model_region.tif");

                    //HOperatorSet.ReadTuple(path + "\\roi_row.tup", out circleParams.rOI_Y);
                    //HOperatorSet.ReadTuple(path + "\\roi_col.tup", out circleParams.rOI_X);
                    //HOperatorSet.ReadTuple(path + "\\roi_dir.tup", out circleParams.circle_Direct);

                    IniConfigHelper.filePath = path + "\\param.ini";

                    //matchParams.startAngle = Convert.ToDouble(IniConfigHelper.ReadIniData("定位参数", "起始角度", "-45"));
                    //matchParams.rangeAngle = Convert.ToDouble(IniConfigHelper.ReadIniData("定位参数", "角度范围", "90"));
                    //matchParams.score = Convert.ToDouble(IniConfigHelper.ReadIniData("定位参数", "分数", "1"));
                    //matchParams.overlap = Convert.ToDouble(IniConfigHelper.ReadIniData("定位参数", "重叠度", "0.5"));
                    //matchParams.numMatchs = Convert.ToInt32(IniConfigHelper.ReadIniData("定位参数", "数量", "1"));

                    //circleParams.circle_Elements = Convert.ToInt32(IniConfigHelper.ReadIniData("测量参数", "搜索点数", "1"));
                    //circleParams.circle_Threshold = Convert.ToInt32(IniConfigHelper.ReadIniData("测量参数", "边缘阈值", "1"));
                    //circleParams.circle_Sigma = Convert.ToDouble(IniConfigHelper.ReadIniData("测量参数", "平滑系数", "1"));
                    //circleParams.circle_Transition = IniConfigHelper.ReadIniData("测量参数", "极性", "max");
                    //circleParams.circle_Point_Select = IniConfigHelper.ReadIniData("测量参数", "点选择", "all");

                    return OperateResult.CreateSuccessResult(matchParams, circleParams);
                }
                catch (Exception ex)
                {
                    return OperateResult.CreateFailResult<MatchParams, CircleParams>(ex.Message);
                }
            }
            else
            {
                return OperateResult.CreateFailResult<MatchParams, CircleParams>("标定文件路径不存在");
            }
        }

        /// <summary>
        /// 获取所有的模板
        /// </summary>
        /// <param name="basePath"></param>
        /// <returns></returns>
        public List<string> GetAllShapeModels(string basePath)
        {
            List<string> result = new List<string>();

            DirectoryInfo directoryInfo = new DirectoryInfo(basePath);

            foreach (var item in directoryInfo.GetDirectories())
            {
                result.Add(item.Name);
            }
            return result;
        }

        /// <summary>
        /// 清除模板
        /// </summary>
        /// <param name="ModelId"></param>
        public void ClearShapeMode(ref HTuple ModelId)
        {
            if (ModelId != null)
            {
                HOperatorSet.ClearShapeModel(ModelId);
                ModelId = null;
            }
        }

    }
}
